/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlutils;

import DTO.viewHistory.Playlists;
import DTO.viewHistory.Songs;
import DTO.viewHistory.Albums;
import DTO.viewHistory.Artists;
import DTO.viewHistory.History;
import DTO.viewHistory.ViewHistory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author TungNT60513
 */
public class XMLUtils implements Serializable {
    // ThuanNH

    private static final String xsdInput = "src/java/schema/";
    private static final String jaxb = "DTO.";
    private static final String destination = "web/xml/";

    // ThuanNH
    public static Document parseDOM(String filePath) {

        Document doc = null;
        try {
            DocumentBuilderFactory bdf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = bdf.newDocumentBuilder();
            File file = new File(filePath);
            doc = db.parse(file);
            return doc;
        } catch (SAXException ex) {
            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return doc;
    }

    //ThuanNH
    //Save data to file XML
    public static void writeXML(Node node, String filePath) {
        try {
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer trans = tff.newTransformer();

            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            Source src = new DOMSource(node);
            File file = new File(filePath);
            Result result = new StreamResult(file);

            trans.transform(src, result);

        } catch (TransformerException ex) {
            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // ThuanNH
    public static Object unmarshallXML(String xsd, String xml) {
        Object rsObject = null;
        try {
            JAXBContext jc = JAXBContext.newInstance(jaxb + "song");
            Unmarshaller u = jc.createUnmarshaller();
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(xsdInput + xsd));
            Validator validator = schema.newValidator();
            InputSource inputFile = new InputSource(new BufferedReader(new FileReader(xml)));
            validator.validate(new SAXSource(inputFile));
            File f = new File(xml);

            rsObject = (Object) u.unmarshal(f);
        } catch (IOException ex) {
            System.out.println("IO Exception error: " + ex.getMessage());
        } catch (SAXException ex) {
            System.out.println("SAX Exception error: " + ex.getMessage());
        } catch (JAXBException ex) {
            System.out.println("JAXB Exception error: " + ex.getMessage());
        } finally {
            return rsObject;
        }
    }

    // ThuanNH
    public static void marshalToXMLFile(Object obj, String fileName) {
        try {
            JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(obj, new File(destination + fileName));

            System.out.println("Generate successfully " + destination + fileName);
        } catch (JAXBException ex) {
            System.out.println("Generate XML error: " + ex.getMessage());
        }
    }

    // TanND
    // Create FO file
    public static void methodTrAx(String xslPath, String xmlPath, String output) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            StreamSource xsltFile = new StreamSource(xslPath);
            Transformer trans = tf.newTransformer(xsltFile);

            StreamSource xmlFile = new StreamSource(xmlPath);
            StreamResult pdfFile = new StreamResult(
                    new FileOutputStream(output));
            trans.transform(xmlFile, pdfFile);
        } catch (TransformerException ex) {
            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // ThuanNH
    // Create XML File
    public static boolean createViewHistoryXML(String path,int d, int m, int w){
        try {
            // new History
            History history = new History();
            history.setAlbums(new Albums());
            history.setArtists(new Artists());
            history.setPlaylists(new Playlists());
            history.setSongs(new Songs());
            history.setDate(BigInteger.valueOf(d));
            // add history to ViewHistory and complete ViewHistory
            ViewHistory vh = new ViewHistory();
            vh.getHistory().add(history);
            vh.setMonth(BigInteger.valueOf(m));
            vh.setWeek(BigInteger.valueOf(w));
            // done then marshall

            JAXBContext jc = JAXBContext.newInstance(vh.getClass());
            Marshaller ms = jc.createMarshaller();
            ms.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            ms.marshal(vh, new File(path));

            return true;
        } catch (JAXBException ex) {
            System.out.println("Create View History XML document successfully.");
            return false;
        } 
    }
}
